//! Serde 示例演示
//!
//! 本模块演示了 serde 库的常用功能，包括：
//! 1. 结构体序列化/反序列化
//! 2. 枚举序列化/反序列化
//! 3. 容器类型（Vec, HashMap）处理
//! 4. 自定义序列化/反序列化
//! 5. 属性使用示例

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// 基本结构体示例
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

/// 元组结构体示例
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Complex(f64, f64);

/// 带有默认值的结构体
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Person {
    name: String,
    #[serde(default)]
    age: u32,
    #[serde(default = "default_email")]
    email: String,
}

fn default_email() -> String {
    "example@example.com".to_string()
}

/// 枚举示例
#[derive(Serialize, Deserialize, Debug, PartialEq)]
enum Animal {
    Dog,
    Cat,
    Bird(String),
}

/// 带有重命名字段的结构体
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
struct Product {
    id: u32,
    name: String,
    #[serde(rename = "desc")]
    description: String,
}

/// 测试基本结构体序列化/反序列化
#[test]
fn test_struct_serialization() {
    let point = Point { x: 1, y: 2 };

    // 序列化
    let serialized = serde_json::to_string(&point).unwrap();
    println!("Serialized Point: {serialized}");
    assert_eq!(serialized, r#"{"x":1,"y":2}"#);

    // 反序列化
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();
    println!("Deserialized Point: {deserialized:?}");
    assert_eq!(point, deserialized);
}

/// 测试元组结构体序列化/反序列化
#[test]
fn test_tuple_struct_serialization() {
    let complex = Complex(1.0, 2.0);

    // 序列化
    let serialized = serde_json::to_string(&complex).unwrap();
    println!("Serialized Complex: {serialized}");
    assert_eq!(serialized, r#"[1.0,2.0]"#);

    // 反序列化
    let deserialized: Complex = serde_json::from_str(&serialized).unwrap();
    println!("Deserialized Complex: {deserialized:?}");
    assert_eq!(complex.0, deserialized.0);
    assert_eq!(complex.1, deserialized.1);
}

/// 测试枚举序列化/反序列化
#[test]
fn test_enum_serialization() {
    let dog = Animal::Dog;
    let bird = Animal::Bird("Parrot".to_string());

    // 序列化
    let dog_serialized = serde_json::to_string(&dog).unwrap();
    let bird_serialized = serde_json::to_string(&bird).unwrap();
    println!("Serialized Dog: {dog_serialized}");
    println!("Serialized Bird: {bird_serialized}");

    // 反序列化
    let dog_deserialized: Animal = serde_json::from_str(&dog_serialized).unwrap();
    let bird_deserialized: Animal = serde_json::from_str(&bird_serialized).unwrap();
    println!("Deserialized Dog: {dog_deserialized:?}");
    println!("Deserialized Bird: {bird_deserialized:?}");

    assert!(matches!(dog_deserialized, Animal::Dog));
    if let Animal::Bird(name) = bird_deserialized {
        assert_eq!(name, "Parrot");
    }
}

/// 测试容器类型（Vec, HashMap）
#[test]
fn test_container_types() {
    // Vec 示例
    let vec = vec![1, 2, 3, 4, 5];
    let vec_serialized = serde_json::to_string(&vec).unwrap();
    println!("Serialized Vec: {vec_serialized}");
    let vec_deserialized: Vec<i32> = serde_json::from_str(&vec_serialized).unwrap();
    assert_eq!(vec, vec_deserialized);

    // HashMap 示例
    let mut map = HashMap::new();
    map.insert("name".to_string(), "Alice".to_string());
    map.insert("city".to_string(), "Beijing".to_string());

    let map_serialized = serde_json::to_string(&map).unwrap();
    println!("Serialized HashMap: {map_serialized}");
    let map_deserialized: HashMap<String, String> = serde_json::from_str(&map_serialized).unwrap();
    assert_eq!(map.get("name"), map_deserialized.get("name"));
    assert_eq!(map.get("city"), map_deserialized.get("city"));
}

/// 测试默认值处理
#[test]
fn test_default_values() {
    // JSON 中缺少 age 和 email 字段
    let json = r#"{"name": "Bob"}"#;
    let person: Person = serde_json::from_str(json).unwrap();
    println!("Deserialized Person with defaults: {person:?}");
    assert_eq!(person.name, "Bob");
    assert_eq!(person.age, 0); // 默认值
    assert_eq!(person.email, "example@example.com"); // 自定义默认值
}

/// 测试字段重命名
#[test]
fn test_field_renaming() {
    let product = Product {
        id: 1,
        name: "Laptop".to_string(),
        description: "A powerful laptop".to_string(),
    };

    let serialized = serde_json::to_string(&product).unwrap();
    println!("Serialized Product: {serialized}");
    // 注意字段被重命名：description -> desc，所有字段变为小写
    assert!(serialized.contains("\"id\":1"));
    assert!(serialized.contains("\"name\":\"Laptop\""));
    assert!(serialized.contains("\"desc\":\"A powerful laptop\""));

    let deserialized: Product = serde_json::from_str(&serialized).unwrap();
    assert_eq!(product.id, deserialized.id);
    assert_eq!(product.name, deserialized.name);
    assert_eq!(product.description, deserialized.description);
}

/// 测试嵌套结构体
#[test]
fn test_nested_structures() {
    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct Company {
        name: String,
        #[serde(rename = "estd")]
        established: u32,
        employees: Vec<Person>,
    }

    let company = Company {
        name: "Tech Corp".to_string(),
        established: 2000,
        employees: vec![
            Person {
                name: "Alice".to_string(),
                age: 30,
                email: "alice@techcorp.com".to_string(),
            },
            Person {
                name: "Bob".to_string(),
                age: 25,
                email: "bob@techcorp.com".to_string(),
            },
        ],
    };

    let serialized = serde_json::to_string_pretty(&company).unwrap();
    println!("Serialized Company:\n{serialized}");

    let deserialized: Company = serde_json::from_str(&serialized).unwrap();
    println!("Deserialized Company: {deserialized:?}");

    assert_eq!(company.name, deserialized.name);
    assert_eq!(company.established, deserialized.established);
    assert_eq!(company.employees.len(), deserialized.employees.len());
}
